package org.luo.lan.common.util;

import lombok.extern.slf4j.Slf4j;
import org.luo.lan.common.config.SslConfig;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * @Auther: luobiao
 * @Date: 2020/9/19 16:49
 * @Description:
 */
@Slf4j
public class SslEngineUtil {

    private static SSLContext getSslContext(String pwd, String jksFilePath) {
        SSLContext sslContext = null;
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            char[] passphrase = pwd.toCharArray();
            ks.load(new FileInputStream(jksFilePath), passphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, passphrase);

            KeyStore ts = KeyStore.getInstance("JKS");
            ts.load(new FileInputStream(jksFilePath), passphrase);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ts);
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } catch (Exception ex) {
            log.error("创建SSLContext出错，jksFilePath={}，ex={}", jksFilePath,ex);
        }
        return sslContext;
    }

    public static SSLEngine getSslEngine(SslConfig sslConfig) {
        SSLEngine sslEngine = getSslContext(sslConfig.getPwd(), sslConfig.getJksFilePath()).createSSLEngine();
        setSslConfig(sslConfig, sslEngine);
        return sslEngine;
    }


    private static void setSslConfig(SslConfig sslConfig, SSLEngine sslEngine) {
        if (sslConfig.isNeedClientAuth() != null) sslEngine.setUseClientMode(sslConfig.isUseClientMode());
        if (sslConfig.isUseClientMode() != null) sslEngine.setNeedClientAuth(sslConfig.isNeedClientAuth());
    }
}
